package com.yc.junit;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class TestRunner {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, InvocationTargetException {
        Class[] testerCLasses = {MathBizTest.class}; //class com.yc.junit.MathBiz
        for (Class testerCLass : testerCLasses) {
            //创建被测试对象
           // System.out.println(testerCLass.newInstance()); com.yc.junit.MathBiz@2acf57e3
            Object tester = testerCLass.newInstance();
            Method[] methods = testerCLass.getMethods();
            List<Method> testMethods=new ArrayList<>();
            //收集测试方法
            for (Method method : methods) {
                if(method.getAnnotation(Test.class)!=null){
                    testMethods.add(method);
                    System.out.println(testMethods);
                }

            }
      /*      //排序 TODO
          testMethods.sort(new Comparator<Method>() {
              @Override
              public int compare(Method o1, Method o2) {
                  Test test1 = o1.getAnnotation(Test.class);
                  Test test2 = o2.getAnnotation(Test.class);
                  return test1.value()- test2.value(); //升序
              }
          });

//lamada表达式
            testMethods.sort(( o1,  o2)-> {
                    Test test1 = o1.getAnnotation(Test.class);
                    Test test2 = o2.getAnnotation(Test.class);
                    return test1.value()- test2.value(); //升序

            });
*/
            //
            testMethods.sort(((o1, o2) -> o1.getAnnotation(Test.class).value()-o2.getAnnotation(Test.class).value()));





            //执行测试
            int success=0;
            int failure=0;
            int errors=0;
            for (Method testMethod : testMethods) {
                try{
                    testMethod.invoke(tester);//默认公有无参
                    success++;
                }catch (InvocationTargetException e){
                    Throwable cause = e.getCause();
                    if(cause instanceof AssertionError){
                        failure++;
                    }else {
                        errors++;
                    }
                }

            }
            System.out.println("测试成功"+success);
            System.out.println("测试失败"+failure);
            System.out.println("测试错误"+errors);
        }
    }
}
